<template>
    <div class="app-container">
        <el-form ref="form" :model="params">
            <div class="params-form params-form-gray">
                <el-form-item label="申请单ID" prop="applyId">
                    <el-input v-model="params.applyId" placeholder="请输入" />
                </el-form-item>
                <el-form-item label="关键词">
                    <el-input v-model="params.applyDes" placeholder="请输入" />
                </el-form-item>
                <el-form-item label="创建时间">
                    <el-date-picker v-model="params.date" type="daterange" start-placeholder="开始时间"
                        end-placeholder="结束时间" value-format="YYYY-MM-DD" />
                </el-form-item>
                <el-form-item>
                    <el-button :icon="Search" type="primary" @click="init">查询</el-button>
                    <el-button :icon="RefreshRight" plain type="primary" @click="reset">重置</el-button>
                </el-form-item>
            </div>
        </el-form>
        <div class="table-add">
            <el-button type="primary" :icon="Plus" @click="openDrawer">新建</el-button>
        </div>
        <div class="table" :style="{ '--colums': 6 }">
            <div class="table-head">
                <div>申请单ID</div>
                <div>描述</div>
                <div>创建时间</div>
                <div>金额</div>
                <div>状态</div>
                <div>操作</div>
            </div>
            <el-empty v-if="!data.length"></el-empty>
            <el-scrollbar max-height="calc(100vh - 450px)">
                <div class="row" v-for="item in data" :key="item.billNoteId">
                    <div>{{ item.slipApplyId }}</div>
                    <div class="desc">{{ item.applyDes }}</div>
                    <div>{{ item.applyTime }}</div>
                    <div>{{ item.applyMoney }}</div>
                    <div><el-tag :type="statusList[item.applyStatus].type">{{ statusList[item.applyStatus].text }}</el-tag></div>
                    <div>
                        <el-button type="primary" link @click="openDrawer(item)">详情</el-button>
                        <el-button type="primary" link @click="openDel(item)">删除</el-button>
                    </div>
                </div>
            </el-scrollbar>
        </div>
        <div class="pagination">
            <el-pagination v-model:current-page="query.current" v-model:page-size="query.size"
                :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper" :total="total"
                @size-change="init" @current-change="init" />
        </div>
        <el-drawer v-model="visible" :with-header="false" @close="close">
            <div class="drawer-content">
                <div class="title-box">
                    <custom-title :title="isNew ? '新建预付款' : '预付款详情'" />
                    <el-icon @click="visible = false">
                        <Close />
                    </el-icon>
                </div>
                <div :class="{ 'params-form-gray': !isNew }" v-if="visible">
                    <el-form :model="addForm" ref="addFormRef" :rules="isNew ? rules : {}" label-width="auto">
                        <el-form-item label="金额" prop="applyMoney">
                            <el-input v-if="isNew" placeholder="请输入金额" v-model="addForm.applyMoney" />
                            <div v-else class="preview">{{ addForm.applyMoney }}</div>
                        </el-form-item>
                        <el-form-item label="关联供应商" prop="partnerId" >
                            <el-select-v2 v-if="isNew" v-model:model-value="addForm.partnerId" filterable remote
                                :remote-method="remoteMethodPartner" :options="options" :props="props"
                                placeholder="请输入名称" @change="changePartner"/>
                            <div v-else class="preview">{{ addForm.partnerName }}</div>
                        </el-form-item>
                        <el-form-item label="支付账号" prop="partnerAccountId" v-if="addForm.partnerId">
                            <div class="form-item-space">
                                <template v-if="isNew">
                                    <el-select v-model="addForm.partnerAccountId">
                                        <template #prefix>
                                            <el-select v-model="payType"
                                                style="width: 100px;border-right:1px solid #D7D8E0;"
                                                @change='addForm.partnerAccountId = ""'>
                                                <el-option v-for="item in payTypeList" :label="item.dictName"
                                                    :value="item.dictName" :key="item.dictId"></el-option>
                                            </el-select>
                                        </template>
                                        <el-option v-for="item in accountList.filter(v => v.dictName == payType)"
                                            :value="item.partnerAccountId" :key="item.partnerAccountId"
                                            :label="item.account"></el-option>
                                    </el-select>
                                    <el-button type="primary" link @click="openAddAccount">新建</el-button>
                                </template>
                                <div v-else class="preview">{{ addForm.account }}</div>
                            </div>
                        </el-form-item>
                        <el-form-item label="描述" prop="applyDes">
                            <el-input v-if="isNew" type="textarea" v-model="addForm.applyDes" placeholder="请输入申请描述" />
                            <div v-else class="preview">{{ addForm.applyDes }}</div>
                        </el-form-item>
                        <el-form-item label="上传图片" prop="applyPicUrls">
                            <div v-if="addForm.fileVos.length||isNew">
                                <el-upload class="avatar-uploader" multiple :show-file-list="false"
                                    :http-request="customRequest">
                                    <div class='list'>
                                        <div class="code" v-for="item, index in addForm.fileVos" :key="item"
                                            @click.stop>
                                            <el-image class="code" :src="item.fileUrl" :preview-src-list="addForm.fileVos.map(v => v.fileUrl)"
                                                :zoom-rate="1.2" :max-scale="7" :min-scale="0.2" :initial-index="index"
                                                fit="cover" hide-on-click-modal />
                                            <div class="del" v-if="isNew">
                                                <el-icon @click.stop="delImg(item)">
                                                    <DeleteFilled />
                                                </el-icon>
                                            </div>
                                        </div>
                                        <el-icon class="upload" v-if="addForm.fileVos.length < 6&& isNew">
                                            <Plus />
                                            <span>点击上传</span>
                                        </el-icon>
                                    </div>
                                </el-upload>
                                <div class="tip" v-if="isNew">注：支持JPG/JPEG/PNG格式，最多上传10张，单张照片不大于30M</div>
                            </div>
                            <div v-else>无</div>
                        </el-form-item>
                    </el-form>
                </div>
            </div>
            <template #footer v-if="isNew">
                <div class="footer-btn">
                    <el-button @click="visible = false">取消</el-button>
                    <el-button type="primary" @click="confirm">确定</el-button>
                </div>
            </template>
        </el-drawer>
        <el-dialog v-model="accountVisible" width="400" center align-center :show-close="false" @close="closeAccount">
            <template #title>
                <custom-title title="新建支付账号" />
            </template>
            <el-form :model="accountForm" label-width="auto" ref="accountFormRef" :rules="accountRules">
                <el-form-item label="支付方式" prop="dictId">
                    <el-select-v2 v-model:model-value="accountForm.dictId" filterable remote
                        :remote-method="remoteMethod" clearable :options="payTypeList"
                        :props="{ label: 'dictName', value: 'dictId' }" placeholder="请输入名称" />
                </el-form-item>
                <el-form-item label="账号" prop="account">
                    <el-input v-model="accountForm.account" placeholder="请输入账号" />
                </el-form-item>
                <el-form-item label="开户银行" prop="bankName">
                    <el-input v-model="accountForm.bankName" placeholder="请输入开户银行" />
                </el-form-item>
                <el-form-item label="户名" prop="accountName">
                    <el-input v-model="accountForm.accountName" placeholder="请输入户名" />
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="footer-btn">
                    <el-button @click="accountVisible = false">取消</el-button>
                    <el-button type="primary" @click="addAccount">确定</el-button>
                </div>
            </template>
        </el-dialog>
        <el-dialog v-model="delVisible" width="400" center align-center :show-close="false">
            <div class="sure">
                <div>
                    <el-icon>
                        <Warning />
                    </el-icon>
                </div>
                <span>是否删除该申请单？</span>
            </div>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="delVisible = false">取 消</el-button>
                    <el-button type="primary" @click="delItem">确 定</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { Search, RefreshRight, Plus } from '@element-plus/icons-vue';
import {delApplication, getApplicationList } from "@/apis/oa/index";
import { addApplication } from "@/apis/oa/advance";
import { ref, onMounted } from "vue";
import { getList as getPartnerAccount,add } from "@/apis/account";

import { ElMessage } from 'element-plus';
import { payTypeDict } from "@/apis/dict/dict";
import { type } from "@/utils/config";
import uploadFile from "@/utils/uploadFile";
import { getPartnerList } from "@/apis/invoices/index";

const props = {
    label: 'name',
    value: 'partnerId',
}
const options = ref([])
const accountForm = ref({})
const accountVisible = ref(false)
const visible = ref(false)
const statusList = {
    1:{
        text:'审核中',
        type:'warning'
    },
    2:{
        text:'已通过',
        type:'success'
    },
    3:{
        text:'已打款',
        type:'primary'
    },
    4:{
        text:'未通过',
        type:'danger'
    }
}
const addFormRef = ref(null);
const formRenderRef = ref(null);
const accountFormRef = ref(null)
const formItemsData = ref([])
const params = ref({
    serviceType: 9,
});
const query = ref({
    current: 1,
    size: 10
});
const payType = ref('')
const total = ref(0)
const isNew = ref(false)
const addForm = ref({
    fileVos:[]
})
const data = ref([]);
const accountList = ref([]);
const openDrawer = async (item) => {
    if (item.slipApplyId) {
        isNew.value = false;
        addForm.value = {...item,fileVos:item.applyPicUrls?item.applyPicUrls.split(',').map(v=>({fileUrl:v})):[]};
    } else {
        isNew.value = true;
    }
    visible.value = true
}
const delVisible = ref(false);
const delId = ref('')
/**
 * 打开删除弹窗
 */
const openDel = (item) => {
    delId.value = item.slipApplyId;
    delVisible.value = true;
}
/**
 * 查询供应商 
 */
const remoteMethodPartner = async (value) => {
    if(!value)return;
    const res = await getPartnerList(2, value);
    options.value = res.data.map(v => ({ ...v, name: type[v.type] + ' : ' + v.name }));
}
/**
 * 打开添加账户弹窗
 */
const openAddAccount = () => {
    payTypeList.value = [];
    accountVisible.value = true;
}
/**
 * 关闭账户弹窗
 */
const closeAccount = () => {
    accountFormRef.value.resetFields()
}
const accountRules = {
    account: [{ required: true, message: '请输入账号', trigger: 'blur' }, { max: 20, message: '开户银行不能超过20个字符', trigger: 'blur' }],
    dictId: [{ required: true, message: '请选择支付方式', trigger: 'blur' }],
    accountName: [{ max: 20, message: '户名不能超过20个字符', trigger: 'blur' }],
    bankName: [{ max: 20, message: '开户银行不能超过20个字符', trigger: 'blur' }],
}
const rules = {
    applyMoney: [
        { required: true, message: '请输入借款金额', trigger: 'blur' },
        { pattern: /^[0-9]+(\.[0-9]{1,2})?$/, message: '请输入正确的金额', trigger: 'blur' }
    ],
    partnerAccountId: [{ required: true, message: '请选择支付账号', trigger: 'blur' }],
    applyDes: [
        { required: true, message: '请输入借款描述', trigger: 'blur' },
        { max: 100, message: '借款描述不能超过100个字符', trigger: 'blur' }
    ],
    partnerId: [{ required: true, message: '请选择', trigger: 'change' }],
};
/**
 * 关闭抽屉
 */
const close = () => {
    addForm.value = {
        fileVos:[]
    };
    formItemsData.value = [];
    addFormRef.value?.resetFields();
    formRenderRef.value?.resetForm();
    accountVisible.value = false;
    payType.value = ''
}
const reset = () => {
    params.value = {};
    init()
}
const payTypeList = ref([])
/**
 * 查询支付方式
 */
const remoteMethod = async (dictName) => {
    const res = await payTypeDict({ status: 1, dictName });
    payTypeList.value = res.data;
}
const init = async () => {
    let applyDateStart = '';
    let applyDateEnd = '';
    if (params.value.date) {
        applyDateStart = params.value.date[0] + ' ' + '00:00:00';
        applyDateEnd = params.value.date[1] + ' ' + '23:59:59';
    } else {
        applyDateStart = undefined
        applyDateEnd = undefined
    }
    const res = await getApplicationList(query.value, { ...params.value, applyDateStart, applyDateEnd });
    total.value = res.data.total;
    data.value = res.data.list;
}
/**
 * 添加账户
 */
const addAccount = () => {
    accountFormRef.value.validate(async (valid) => {
        if (valid) {
            const res = await add({ ...accountForm.value, status: 1,partnerId:addForm.value.partnerId });
            if (res.code == 200) {
                accountVisible.value = false;
                ElMessage.success('添加成功');
                getAccount()

            }
        }
    })
}

/**
 * 删除图片
 */
const delItem = async () => {
    const res = await delApplication(delId.value);
    if (res.code == 200) {
        init()
        ElMessage.success('删除成功');
        delVisible.value = false;
    }
}
const verify = () => {
    let arr = [];
    arr.push(new Promise((resolve) => {
        addFormRef.value.validate((valid) => {
            resolve(valid)
        })
    }))
    return Promise.all(arr);
}

/**
 * 自定义上传
 */
const customRequest = async options => {
    const type = ['image/jpg', 'image/jpeg', 'image/png'];
    const { file } = options;
    if (!type.includes(file.type)) {
        ElMessage.error('图片格式错误')
        return false
    } else if (file.size / 1024 / 1024 > 30) {
        ElMessage.error('图片大小不能超过30MB!')
        return false
    }
    const fileInfo = await uploadFile(options);
    if (addForm.value.fileVos.length < 10) {
        addForm.value.fileVos.push({ fileUrl: fileInfo.url, fileName: fileInfo.name, fileId: fileInfo.uid });
    } else {
        if (!isImgMax.value) ElMessage.error('最多上传10张图片');
        isImgMax.value = true;
    }
};
/**
 * 抽屉确定
 */
const confirm = async () => {
    if ((await verify()).every(v => v)) {
        const res = await addApplication({
            ...addForm.value
        });
        if (res.code == 200) {
            init();
            ElMessage.success('添加成功');
            visible.value = false;
        }
    }
}
const getAccount = async () => {
    const res = await getPartnerAccount({current:1,size:100000},{partnerType:2,partnerId:addForm.value.partnerId,status:1});
    accountList.value = res.data.list;
};
const changePartner=()=>{
    addForm.value.partnerAccountId = '';
    getAccount()
}
const isImgMax = ref(false);
const delImg = (index) => {
    addForm.value.fileVos.splice(index, 1);
    if (addForm.value.fileVos.length < 6) isImgMax.value = false;
}
onMounted(() => {
    init();
    remoteMethod();
})
</script>

<style lang="scss" scoped>
@import '../index.scss';
</style>

